<template>
	<a-modal
		:visible="props.visible"
		:title="newContract.id ? '重新发起' : '新增合同'"
		:footer="null"
		:width="1100"
		@cancel="emits('update:visible', false)"
	>
		<div class="px-10">
			<a-steps :current="step" size="small">
				<a-step title="选择场景" />
				<a-step title="签约方维护" />
				<a-step title="产品维护" />
				<a-step v-if="newContract.signMethod === '1'" title="资料上传" />
			</a-steps>
		</div>
		<!-- 选择场景步骤 -->
		<div v-if="step === 0" class="p-10 min-h-[450px]">
			<h3 style="font-weight: 600">
				<span>选择签约方式</span>
				<span class="pl-[20px] text-yellow-500">
					<exclamation-circle-outlined />
					<span class="pl-[4px] font-[400] text-[14px]">{{
						newContract.signMethod === '0'
							? '该方式适用于电子合同、电子支付签约场景，可提升合同签约效率'
							: '该方式适用于线下先签约、线上再提单的签约场景'
					}}</span>
				</span>
			</h3>
			<a-form label-align="right" :label-col="{ style: { width: '100px' } }" class="ml-10 mt-6">
				<a-form-item label="签约方式">
					<a-radio-group v-model:value="newContract.signMethod" @change="onSignMethodChange">
						<a-radio value="0">电子合同</a-radio>
						<a-radio value="1">纸质合同</a-radio>
					</a-radio-group>
				</a-form-item>
			</a-form>
			<h3 style="font-weight: 600">选择签约场景</h3>
			<a-form label-align="right" :label-col="{ style: { width: '100px' } }" class="ml-10 mt-6">
				<a-form-item label="签约场景">
					<a-radio-group v-if="newContract.signMethod === '0'" v-model:value="newContract.signPayment">
						<a-radio value="OnlineSignedPaid">线上签约并支付</a-radio>
						<a-radio value="OnlineSignedUnpaid">线上签约不支付</a-radio>
						<a-radio value="OfflineSignedPaid">线下签约并收款</a-radio>
					</a-radio-group>
					<span v-else-if="newContract.signMethod === '1'">线下签约提单</span>
				</a-form-item>
				<a-form-item label="付款类型">
					<a-radio-group v-model:value="newContract.paymentMethod">
						<a-radio value="FULL">全款</a-radio>
						<a-radio value="DEPOSIT">定金</a-radio>
					</a-radio-group>
				</a-form-item>
			</a-form>
		</div>
		<!-- 签约方维护步骤 -->
		<div v-if="step === 1" class="p-10 min-h-[450px]">
			<h3>
				<span style="font-weight: 600">合同签署方</span>
				<span class="ml-[16px] mb-[20px] text-red-500 font-extralight text-[14px]"
					>（甲方若为企业，甲方名称必须与工商注册名称一致，否则无法进行合同签约）</span
				>
			</h3>
			<a-row :gutter="16">
				<a-col :span="12">
					<a-form label-align="right" :label-col="{ style: { width: '120px' } }">
						<a-form-item label="甲方">
							<a-select
								v-model:value="firstPartyData"
								:options="firstPartyOptions"
								label-in-value
								show-search
								:filter-option="firstPartyFilterOption"
								:open="firstPartyOpen"
								placeholder="请输入关键字"
								:disabled="!!props.from"
								@select="firstPartySelect"
								@search="firstPartySearch"
							></a-select>
						</a-form-item>
						<a-form-item label="客户编号">
							<a-select
								v-model:value="customerRefData"
								:options="customerRefOptions"
								label-in-value
								show-search
								:filter-option="customerRefFilterOption"
								:open="customerRefOpen"
								placeholder="输入客户编号精确搜索客户"
								:disabled="!!props.from"
								@select="customerRefSelect"
								@search="customerRefSearch"
							></a-select>
						</a-form-item>
						<a-form-item label="甲方联系人/法人">
							<a-input-group v-if="newContract.signMethod === '0' && newContract.customerType === 1" compact>
								<a-select v-model:value="newContract.signType" class="!w-[100px]">
									<a-select-option value="0">企业法人</a-select-option>
									<a-select-option value="1">经办人</a-select-option>
								</a-select>
								<a-input v-model:value="newContract.firstPartyPerson" class="!w-[258px]"></a-input>
							</a-input-group>
							<a-input v-else v-model:value="newContract.firstPartyPerson"></a-input>
						</a-form-item>
						<a-form-item label="联系电话">
							<a-input
								v-model:value="newContract.firstPartyMobile"
								autocomplete="off"
								@focus="showFirstMobile = true"
								@blur="firstBlur"
							></a-input>
							<div
								v-if="showFirstMobile"
								class="w-full bg-white max-h-[100px] absolute z-[999] overflow-auto shadow-md"
							>
								<div
									v-for="(item, index) in firstPartyMobileOptions"
									:key="index"
									class="cursor-pointer text-gray-500 my-[2px] ml-2"
									@click.stop="selectFirstMobile(item)"
								>
									<span>{{ item.label }}</span>
								</div>
							</div>
						</a-form-item>
						<a-form-item label="书面送达地址">
							<a-input v-model:value="newContract.firstPartyAddress"></a-input>
						</a-form-item>
					</a-form>
				</a-col>
				<a-col :span="12">
					<a-form label-align="right" :label-col="{ style: { width: '126px' } }">
						<a-form-item label="乙方">
							<a-select
								v-model:value="secondPartyData"
								:options="partyOptions"
								label-in-value
								placeholder="请选择"
								@change="partyChange"
							></a-select>
						</a-form-item>
						<a-form-item label="乙方联系人">
							<a-input v-model:value="newContract.secondPartyPerson"></a-input>
						</a-form-item>
						<a-form-item label="联系电话">
							<a-input v-model:value="newContract.secondPartyMobile"></a-input>
						</a-form-item>
						<a-form-item label="书面送达地址">
							<span>{{ newContract.secondPartyAddress }}</span>
						</a-form-item>
					</a-form>
				</a-col>
			</a-row>
		</div>
		<!-- 产品维护步骤 -->
		<div v-if="step === 2" class="p-10 min-h-[450px]">
			<h3 style="font-weight: 600">服务事项</h3>
			<a-form class="serveForm">
				<a-form-item v-if="newContract.signMethod === '0'" label="合同模板">
					<a-select
						class="!w-[620px]"
						v-model:value="templateValue"
						label-in-value
						:options="templateNameOptions"
						@change="templateChange"
					></a-select>
				</a-form-item>
				<a-form-item label="服务类目">
					<draggable :list="categoryIdsList" item-key="dataIndex" animation="300">
						<template #item="{ index }">
							<div>
								<div class="s-tool-column-item mb-[12px]">
									<div class="s-tool-column-handle layout-items-center">
										<more-outlined />
										<more-outlined />
									</div>
									<a-cascader
										v-model:value="categoryIdsList[index]"
										:options="categoryOptions"
										placeholder="请选择"
										class="!w-[600px]"
										:allow-clear="false"
										:disabled="newContract.signMethod === '0' && !templateValue.value"
										:show-search="{ filter: categoryFilter }"
										@change="(value, selectedOptions) => onCategoryChange(value, selectedOptions, index)"
									/>

									<a-button
										v-if="index === categoryIdsList.length - 1"
										type="link"
										size="small"
										class="ml-[8px]"
										:disabled="newContract.signMethod === '0' && !templateValue.value"
										@click="onCategoryAdd"
									>
										<template #icon><plus-outlined /></template>
										新增
									</a-button>
									<a-button
										v-show="!(categoryIdsList.length === 1 && !index)"
										type="link"
										size="small"
										class="ml-[8px]"
										@click="onCategoryRemove(index)"
									>
										<template #icon><delete-outlined /></template>
										删除
									</a-button>
								</div>
								<!-- 全款 -->
								<template v-if="newContract.paymentMethod === 'FULL'">
									<!-- 代办业务 ONE_TIME -->
									<div v-if="categoryTypeList[index].projectType === 1" class="mb-[12px]">
										<div class="pl-[20px] text-blue-500">代办业务</div>
										<div class="flex flex-wrap gap-x-[30px] gap-y-[10px] pl-[40px]">
											<div>
												<span>订单金额：</span>
												<a-input-number
													v-model:value="categoryTypeList[index].orderAmount"
													:precision="2"
													:step="0.01"
													:min="0"
													controls-position="right"
													placeholder="请输入"
												/>
											</div>
										</div>
									</div>
									<!-- 续费业务(周期业务) PERIODIC -->
									<div v-else-if="categoryTypeList[index].projectType === 2" class="mb-[12px]">
										<div class="pl-[20px] text-blue-500">周期业务</div>
										<div class="flex flex-wrap gap-x-[30px] gap-y-[10px] pl-[40px]">
											<div>
												<span>订单金额：</span>
												<a-input-number
													v-model:value="categoryTypeList[index].orderAmount"
													:precision="2"
													:step="0.01"
													:min="0"
													controls-position="right"
													placeholder="请输入"
												/>
											</div>
											<div>
												<span>服务时长(月)：</span>
												<a-input-number
													v-model:value="categoryTypeList[index].serviceLife"
													:min="1"
													controls-position="right"
													placeholder="请输入"
												/>
											</div>
											<div>
												<span>赠送时长(月)：</span>
												<a-input-number
													v-model:value="categoryTypeList[index].giveMonth"
													:min="0"
													controls-position="right"
													placeholder="请输入"
												/>
											</div>
											<div>
												<span>开始服务月：</span>
												<a-date-picker
													v-model:value="categoryTypeList[index].serviceStime"
													picker="month"
													valueFormat="YYYY-MM"
													placeholder="请选择"
													:disabled-date="(current) => disabledStartDate(current, index)"
												/>
											</div>
											<div class="leading-[32px]">
												<span>结束服务月：</span>
												<span>{{ serviceEndTime(index) }}</span>
											</div>
										</div>
									</div>
								</template>
								<!-- 定金 -->
								<template v-else-if="newContract.paymentMethod === 'DEPOSIT'">
									<!-- 代办业务 ONE_TIME -->
									<div v-if="categoryTypeList[index].projectType === 1" class="mb-[12px]">
										<div class="text-blue-500">代办业务</div>
										<div class="flex flex-wrap gap-x-[30px] gap-y-[10px] pl-[40px]">
											<div>
												<span>订单金额：</span>
												<a-input-number
													v-model:value="categoryTypeList[index].orderAmount"
													:precision="2"
													:step="0.01"
													:min="0"
													controls-position="right"
													placeholder="请输入"
												/>
											</div>
											<div>
												<span>定金金额：</span>
												<a-input-number
													v-model:value="categoryTypeList[index].depositAmount"
													:precision="2"
													:step="0.01"
													:min="0"
													controls-position="right"
													placeholder="请输入"
												/>
											</div>
											<div class="leading-[32px]">
												<span>尾款金额：</span>
												<span>{{ balanceAmount(index) }}</span>
											</div>
										</div>
									</div>
									<!-- 续费业务(周期业务) PERIODIC -->
									<div v-else-if="categoryTypeList[index].projectType === 2" class="mb-[12px]">
										<div class="text-blue-500">周期业务</div>
										<div class="flex flex-wrap gap-x-[30px] gap-y-[10px] pl-[40px]">
											<div>
												<span>订单金额：</span>
												<a-input-number
													v-model:value="categoryTypeList[index].orderAmount"
													:precision="2"
													:step="0.01"
													:min="0"
													controls-position="right"
													placeholder="请输入"
												/>
											</div>
											<div>
												<span>定金金额：</span>
												<a-input-number
													v-model:value="categoryTypeList[index].depositAmount"
													:precision="2"
													:step="0.01"
													:min="0"
													controls-position="right"
													placeholder="请输入"
												/>
											</div>
											<div class="leading-[32px]">
												<span>尾款金额：</span>
												<span>{{ balanceAmount(index) }}</span>
											</div>
											<div>
												<span>服务时长(月)：</span>
												<a-input-number
													v-model:value="categoryTypeList[index].serviceLife"
													:min="1"
													controls-position="right"
													placeholder="请输入"
												/>
											</div>
											<div>
												<span>赠送时长(月)：</span>
												<a-input-number
													v-model:value="categoryTypeList[index].giveMonth"
													:min="0"
													controls-position="right"
													placeholder="请输入"
												/>
											</div>
											<div>
												<span>开始服务月：</span>
												<a-date-picker
													v-model:value="categoryTypeList[index].serviceStime"
													picker="month"
													valueFormat="YYYY-MM"
													placeholder="请选择"
													:disabled-date="(current) => disabledStartDate(current, index)"
												/>
											</div>
											<div class="leading-[32px]">
												<span>结束服务月：</span>
												<span>{{ serviceEndTime(index) }}</span>
											</div>
										</div>
									</div>
								</template>
							</div>
						</template>
					</draggable>
				</a-form-item>
				<a-form-item v-if="categoryIdsList.length && categoryTypeList.some((item) => item.projectType)">
					<div v-if="newContract.paymentMethod === 'FULL'" class="mb-[12px]">
						<div class="text-blue-500">订单合计</div>
						<div class="flex flex-wrap gap-x-[30px] gap-y-[10px] pl-[70px]">
							<div>
								<span>合同总金额：</span>
								<span>{{ contractAmountSum }}</span>
							</div>
						</div>
					</div>
					<div v-if="newContract.paymentMethod === 'DEPOSIT'" class="mb-[12px]">
						<div class="text-blue-500">订单合计</div>
						<div class="flex flex-wrap gap-x-[30px] gap-y-[10px] pl-[70px]">
							<div class="leading-[32px]">
								<span>合同总金额：</span>
								<span>{{ contractAmountSum }}</span>
							</div>
							<div class="leading-[32px]">
								<span>定金总金额：</span>
								<span>{{ depositAmountSum }}</span>
							</div>
							<div class="leading-[32px]">
								<span>尾款总金额：</span>
								<span>{{ balancePaymentSum }}</span>
							</div>
							<div>
								<span>尾款支付时间：</span>
								<a-date-picker
									v-model:value="newContract.balancePaymentTime"
									valueFormat="YYYY-MM-DD"
									format="YYYY-MM-DD"
									placeholder="请选择"
								/>
							</div>
						</div>
					</div>

					<div v-if="newContract.contractType === 'TRANS'" class="mb-[12px]">
						<div class="text-blue-500">订单抵扣合计</div>
						<div class="flex flex-wrap gap-x-[30px] gap-y-[10px] pl-[70px]">
							<div class="leading-[32px]">
								<span>转换合同抵扣金额：</span>
								<span>{{ newContract.transDeductionAmount }}</span>
							</div>
							<div class="leading-[32px]">
								<span>本次合同需支付金额：</span>
								<span>{{
									Math.max(0, parseFloat(contractAmountSum) - parseFloat(newContract.transDeductionAmount)).toFixed(2)
								}}</span>
							</div>
							<div class="leading-[32px]">
								<span>合同剩余金额：</span>
								<span>{{
									Math.max(0, parseFloat(newContract.transDeductionAmount) - parseFloat(contractAmountSum)).toFixed(2)
								}}</span>
							</div>
						</div>
					</div>
				</a-form-item>
				<a-form-item label="备注">
					<a-textarea v-model:value="newContract.remark" :rows="4" placeholder="请填写合同备注，没有则写无" />
				</a-form-item>
			</a-form>
		</div>
		<!-- 资料上传步骤 -->
		<div v-if="step === 3 && newContract.signMethod === '1'" class="p-10 min-h-[450px]">
			<h3 style="font-weight: 600">资料上传</h3>
			<a-form label-align="right" :label-col="{ style: { width: '100px' } }" class="ml-10 mt-6">
				<a-form-item label="合同照片">
					<xn-upload
						ref="contractImgRef"
						list-type="picture-card"
						:before-upload="beforeUpload"
						:uploadNumber="9"
						:multiple="true"
						accept="image/*,.pdf"
						@uploadDone="onContractUploadDone"
					/>
				</a-form-item>
				<a-form-item label="付款凭证">
					<xn-upload
						ref="voucherImgRef"
						list-type="picture-card"
						:before-upload="beforeUpload"
						:uploadNumber="9"
						:multiple="true"
						accept="image/*,.pdf"
						@uploadDone="onPayUploadDone"
					/>
				</a-form-item>
			</a-form>
		</div>
		<!-- 维护完成步骤 -->
		<!-- <div v-if="step === 4" class="p-10 flex flex-col justify-center items-center text-center min-h-[400px]">
			<h2>恭喜，合同维护成功！</h2>
			<div>您还可以进行合同<a-button class="ml-2">预览</a-button></div>
		</div> -->
		<div class="flex justify-center gap-6">
			<a-button v-if="step > 0" @click="toPrev">上一步</a-button>
			<a-button v-if="step < 4" type="primary" :loading="subLoading" @click="toNext">下一步</a-button>
		</div>
	</a-modal>
	<a-modal
		v-model:visible="contractWrite"
		width="100%"
		:footer="false"
		:closable="false"
		style="top: 0; max-width: 100vw; padding-bottom: 0; min-height: 100vh"
		:bodyStyle="{ width: '100vw', height: '100vh' }"
	>
		<iframe :src="iframeUrl" frameborder="0" style="width: 100%; height: calc(100vh - 110px)"></iframe>
		<div class="text-center"><a-button @click="closeContract">返回</a-button></div>
	</a-modal>

	<!-- 添加附件信息 -->
	<el-dialog
		custom-class="declaration-dialog"
		title="添加附件信息"
		v-model="declarationVisible"
		:close-on-click-modal="false"
		width="1200px"
		@close="declarationVisible = false"
	>
		<div style="position: relative">
			<p style="position: absolute; right: 0; color: #e6a23c">合同已创建，您可以继续添加以下附件信息。</p>
			<el-tabs v-model="activeName">
				<el-tab-pane
					v-if="declarationVisible && (isTenantOderControls === 0 || isTenantOderControls === 2)"
					label="添加报单绩效信息"
					name="1"
				>
					<customs-declaration :contractInfo="newContract"></customs-declaration>
				</el-tab-pane>
				<el-tab-pane
					v-if="declarationVisible && (isTenantOderControls === 0 || isTenantOderControls === 1)"
					label="添加客户派单信息表"
					name="2"
				>
					<customer-scheduling :contractInfo="newContract"></customer-scheduling>
				</el-tab-pane>
			</el-tabs>
		</div>
		<!-- <div slot="footer">
			<el-button size="small" @click="declarationVisible=false">关闭</el-button>
		</div> -->
	</el-dialog>
</template>
<script setup>
	import tool from '@/utils/tool'
	import contractApi from '@/api/biz/bizContractApi'
	import erpApi from '@/api/biz/bizCommonApi'
	import claimApi from '@/api/biz/claimApi'
	import { message, Modal, Upload } from 'ant-design-vue'
	import erpProjectApi from '@/api/erp/erpProjectApi'
	import draggable from 'vuedraggable-es'
	import router from '@/router'
	import dayjs from 'dayjs'
	import customerScheduling from '@/views/biz/contractManagement/customerScheduling.vue'
	import customsDeclaration from '@/views/biz/contractManagement/customsDeclaration.vue'
	import customerQwOrderApi from '@/api/biz/customerQwOrderApi'

	const props = defineProps({
		visible: {
			type: Boolean,
			default: false
		},
		info: {
			type: Object,
			default: () => null
		},
		from: {
			type: Number,
			default: 0 // 0-合同管理 1-客户管理
		}
	})
	const emits = defineEmits(['update:visible', 'finished'])

	watch(
		() => props.visible,
		(val) => {
			if (val) {
				getFirstParty()
				getContractPartbList()

				step.value = 0
				if (props.info) {
					const categoryData = props.info.list.reduce(
						(total, item) => {
							total.map[`${item.serviceClassId}-${item.serviceTypeId}-${item.serviceProjectId}`] = [
								{
									label: item.serviceClassName,
									value: item.serviceClassId
								},
								{
									label: item.serviceTypeName,
									value: item.serviceTypeId
								},
								{
									label: item.serviceProjectName,
									value: item.serviceProjectId
								}
							]
							total.list.push([
								parseInt(item.serviceClassId),
								parseInt(item.serviceTypeId),
								parseInt(item.serviceProjectId)
							])
							total.newList.push({
								...item,
								projectType: { ONE_TIME: 1, PERIODIC: 2, NOSERVICE: 3 }[item.businessType]
							})
							return total
						},
						{ map: {}, list: [], newList: [] }
					)
					categoryIdsList.value = categoryData.list
					categoryTypeList.value = categoryData.newList
					Object.assign(categoryIdsMap, categoryData.map)

					firstPartyData.value = {
						label: props.info.firstParty,
						value: props.info.customerCode
					}
					customerRefData.value = {
						label: props.info.customerRef || '',
						value: props.info.customerCode
					}
					secondPartyData.value = {
						label: props.info.secondPartyName,
						value: props.info.secondPartyId
					}

					newContract.value = {
						...props.info
					}
					templateValue.value = {
						label: props.info.templateName,
						value: props.info.templateId
					}
				} else {
					categoryIdsList.value = [[]]
					categoryTypeList.value = [{}]
					Object.assign(categoryIdsMap, {})

					firstPartyData.value = null
					customerRefData.value = null
					secondPartyData.value = null

					newContract.value = tool.deepClone(defaultNewContract)
					templateValue.value = { value: '', label: '' }
				}

				iframeUrl.value = ''
				activeName.value = '1'
				isTenantOderControls.value = null

				const { name, mobile } = tool.data.get('USER_INFO')
				newContract.value.secondPartyPerson = name
				newContract.value.secondPartyMobile = mobile

				// 获取提单配置
				customerQwOrderApi
					.getTenantOderControls({
						tenantId: tool.data.get('loginData').tenantId
					})
					.then((res) => {
						if (res) {
							isTenantOderControls.value = res.type
						}
					})
			}
		}
	)

	const serviceEndTime = computed(() => (index) => {
		const { serviceLife, giveMonth, serviceStime } = categoryTypeList.value[index]
		return serviceStime
			? dayjs(serviceStime)
					.add((parseInt(serviceLife) || 0) + (parseInt(giveMonth) || 0) - 1, 'month')
					.format('YYYY-MM')
			: ''
	})
	const balanceAmount = computed(() => (index) => {
		const { orderAmount, depositAmount } = categoryTypeList.value[index]
		return (orderAmount ? parseFloat(orderAmount) - (parseFloat(depositAmount) || 0) : 0).toFixed(2)
	})

	const contractAmountSum = computed(() =>
		categoryTypeList.value
			.reduce((total, item) => total + (item.orderAmount ? parseFloat(item.orderAmount) : 0), 0)
			.toFixed(2)
	)
	const depositAmountSum = computed(() =>
		categoryTypeList.value
			.reduce((total, item) => total + (item.depositAmount ? parseFloat(item.depositAmount) : 0), 0)
			.toFixed(2)
	)
	const balancePaymentSum = computed(() =>
		categoryTypeList.value.reduce((total, item, index) => total + parseFloat(balanceAmount.value(index)), 0).toFixed(2)
	)

	/**
	 * ====================
	 *       基本逻辑
	 * ====================
	 */
	const step = ref(0)
	const businessOptions = tool.dictList('BUSINESS_TYPE')
	const defaultNewContract = {
		id: null,
		signMethod: '0',
		signPayment: 'OnlineSignedPaid',
		paymentMethod: 'FULL',
		templateId: '',
		templateName: '',
		serviceCategory: '',
		serviceCategoryId: '',
		customerRef: '',
		firstParty: '',
		firstPartyPerson: '',
		firstPartyMobile: '',
		firstPartyAddress: '',
		signType: '1',
		secondPartyName: '',
		secondPartyPerson: '',
		secondPartyAddress: '',
		secondPartyMobile: '',
		customerType: '',
		secondPartyId: '',
		customerCode: '',
		list: [],
		balancePaymentTime: '',
		contractImg: '',
		voucherImg: '',
		remark: ''
	}
	const newContract = ref(tool.deepClone(defaultNewContract))

	/**
	 * 选择签约方式
	 */
	const onSignMethodChange = ({ target: { value } }) => {
		if (value === '0') {
			newContract.value.signPayment = 'OnlineSignedPaid'
		} else if (value === '1') {
			newContract.value.signPayment = 'OfflineSignedBill'
		}

		newContract.value.templateId = ''
		newContract.value.templateName = ''
		categoryIdsList.value = [[]]
		categoryTypeList.value = [{}]
		Object.assign(categoryIdsMap, {})
	}

	/**
	 * 选择模板处理数据
	 */
	const templateNameOptions = ref([])
	const templateValue = ref({ value: '', label: '' })
	const tempTemplateList = ref([])
	const requestTemplateList = async () => {
		const res = await contractApi.getBusinessTemplateList({})
		tempTemplateList.value = JSON.parse(JSON.stringify(res))
		templateNameOptions.value = res.map((item) => {
			return {
				label: item.templateName,
				value: item.templateId
			}
		})
	}
	const templateChange = (select) => {
		categoryIdsList.value = [[]]
		categoryTypeList.value = [{}]
		Object.assign(categoryIdsMap, {})
		newContract.value.list = []

		newContract.value.templateName = select.label
		newContract.value.templateId = select.value

		const templateData = tempTemplateList.value.find((item) => item.templateId === select.value)
		if (templateData) {
			requestServiceProjectListByTemplateId(templateData.id)
		}
	}
	/**
	 * 服务类目选择处理数据格式
	 */
	const categoryOptions = ref([])
	const categoryIdsList = ref([[]])
	const categoryTypeList = ref([{}])
	const categoryIdsMap = reactive({})
	const disabledStartDate = (current, index) => {
		const categoryTypeData = categoryTypeList.value[index]
		if (!categoryTypeData) return false
		const { endExitsTime } = categoryTypeData
		return endExitsTime && current && current < dayjs(endExitsTime, 'YYYY-MM').endOf('month')
	}
	const requestServiceProjectList = () => {
		erpProjectApi.serviceProjectTree().then((res) => {
			categoryOptions.value = res
		})
	}
	const requestServiceProjectListByTemplateId = (templateId) => {
		erpProjectApi.serviceProjectTreeByTemplateId(templateId).then((res) => {
			categoryOptions.value = res
		})
	}

	const onCategoryAdd = () => {
		categoryIdsList.value.push([])
		categoryTypeList.value.push({})
	}
	const onCategoryRemove = (index) => {
		categoryIdsList.value.splice(index, 1)
		categoryTypeList.value.splice(index, 1)
	}

	const categoryFilter = (inputValue, path) => {
		return path.some((option) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
	}
	const onCategoryChange = (value, selectedOptions, index) => {
		console.log(value, selectedOptions, index)
		contractApi
			.getServiceProjectMoreInfo({
				customerCode: newContract.value.customerCode,
				projectId: value[2]
			})
			.then((res1) => {
				if (res1.projectType === '1' && res1.process === '2') {
					// 获取代办业务有无办理步骤 1-有 2-没有
					message.warning('请先维护办理步骤，再选择服务类目')
					delete categoryIdsMap[[`${value[0]}-${value[1]}-${value[2]}`]]
					categoryIdsList.value[index] = []
					categoryTypeList.value[index] = {}
					return
				}

				erpProjectApi.serviceTypeByProjectId(value[2]).then((res) => {
					categoryIdsMap[`${value[0]}-${value[1]}-${value[2]}`] = selectedOptions
					categoryIdsList.value[index] = value
					// projectType	服务类别（1-代办服务，2-续费服务，3-无需服务）
					categoryTypeList.value[index] = {
						...res,
						orderAmount: null,
						depositAmount: null,
						balancePayment: null,
						serviceStime: null,
						serviceEtime: null,
						serviceLife: null,
						giveMonth: res.projectType === 1 ? null : 0
					}

					if (res1.projectType === '2') {
						// 获取续费业务开始年月截止时间
						categoryTypeList.value[index].endExitsTime = res1.endTime
					}
				})
			})
	}

	/**
	 * 获取甲方列表
	 */
	const firstPartyOpen = ref(false)
	const firstPartyData = ref(null)
	const firstPartyOptions = ref([])
	const firstPartyFilterOption = (input, option) => {
		return option.label.indexOf(input) >= 0
	}
	const getFirstParty = () => {
		contractApi.getFirstPartyList().then((res) => {
			firstPartyOptions.value = res.map((item) => {
				return {
					...item,
					value: item.customerCode,
					label: item.customerName
				}
			})
			customerRefOptions.value = res.map((item) => {
				return {
					...item,
					value: item.customerCode,
					label: item.customerRef || '---'
				}
			})
		})
	}
	const firstPartyMobileOptions = ref([])
	const firstPartyFn = (option) => {
		firstPartyOpen.value = false
		customerRefOpen.value = false
		newContract.value.customerCode = option.customerCode
		newContract.value.customerType = option.customerType // 1-企业 2-法人
		newContract.value.firstParty = option.customerName
		newContract.value.customerRef = option.customerRef
		newContract.value.firstPartyAddress = option.customerAddress
		newContract.value.firstPartyPerson = option.contactPerson
		newContract.value.firstPartyMobile = option.contactPhone
		newContract.value.signType = newContract.value.signMethod === '0' && option.customerType === 1 ? '1' : ''
		claimApi.getCompanyPersons({ code: option.customerCode }).then((res) => {
			firstPartyMobileOptions.value = res.map((item) => {
				return {
					value: item.contactsPhone,
					label: item.contactsName + ' ' + item.contactsPhone,
					name: item.contactsName
				}
			})
		})
	}
	const firstPartySelect = (value, option) => {
		firstPartyFn(option)
		customerRefData.value = option.customerRef ? { label: option.customerRef, value: option.customerCode } : null
	}
	const firstPartySearch = (value) => {
		firstPartyOpen.value = !!value
	}

	/**
	 * 甲方编号
	 */
	const customerRefOpen = ref(false)
	const customerRefData = ref(null)
	const customerRefOptions = ref([])
	const customerRefFilterOption = (input, option) => {
		return option.customerRef === input
	}
	const customerRefSelect = (value, option) => {
		firstPartyFn(option)
		firstPartyData.value = { label: option.customerName, value: option.customerCode }
	}
	const customerRefSearch = (value) => {
		customerRefOpen.value = !!value
	}

	const showFirstMobile = ref(false)
	const selectFirstMobile = (item) => {
		newContract.value.firstPartyMobile = item.value
		newContract.value.firstPartyPerson = item.name
		showFirstMobile.value = false
	}
	const firstBlur = () => {
		setTimeout(() => {
			showFirstMobile.value = false
		}, 200)
	}
	/**
	 * 乙方信息列表获取
	 */
	const secondPartyData = ref(null)
	const partyOptions = ref([])
	const getContractPartbList = () => {
		contractApi.getContractPartbList().then((res) => {
			partyOptions.value = res.map((item) => {
				return {
					...item,
					value: item.id,
					label: item.partyName
				}
			})
		})
	}
	const partyChange = (select) => {
		newContract.value.secondPartyId = select.option.id
		newContract.value.secondPartyName = select.option.partyName
		newContract.value.secondPartyAddress = select.option.partyAddress
	}

	/**
	 * 资料上传
	 */
	const contractImgRef = ref(null)
	const voucherImgRef = ref(null)
	const beforeUpload = (file) => {
		const isJpgOrPng =
			file.type === 'image/jpg' ||
			file.type === 'image/jpeg' ||
			file.type === 'image/png' ||
			file.type === 'application/pdf'
		if (!isJpgOrPng) {
			message.error('只能上传JPG/PNG/PDF格式的图片!')
		}
		const isLt10M = file.size / 1024 / 1024 < 10
		if (!isLt10M) {
			message.error('图片大小必须小于10MB!')
		}
		return (isJpgOrPng && isLt10M) || Upload.LIST_IGNORE
	}
	const onContractUploadDone = () => {
		newContract.value.contractImg = contractImgRef.value
			.uploadFileList()
			.map((item) => item.url)
			.join(',')
	}
	const onPayUploadDone = () => {
		newContract.value.voucherImg = voucherImgRef.value
			.uploadFileList()
			.map((item) => item.url)
			.join(',')
	}

	const fileCommonFn = () => {
		// 资料上传
		if (step.value === 3 && newContract.value.signMethod === '1') {
			nextTick(() => {
				const contractImgList = newContract.value.contractImg
					? newContract.value.contractImg.split(',').map((item) => ({ url: item }))
					: []
				contractImgRef.value.resetFileList(contractImgList)

				const voucherImgList = newContract.value.voucherImg
					? newContract.value.voucherImg.split(',').map((item) => ({ url: item }))
					: []
				voucherImgRef.value.resetFileList(voucherImgList)
			})
		}
	}

	/**
	 * 下一步操作
	 */
	const iframeUrl = ref('')
	const contractWrite = ref(false)
	const subLoading = ref(false)
	const toPrev = () => {
		step.value--

		fileCommonFn()
	}
	const toNext = async () => {
		// 测试
		// if (!step.value) {
		// 	newContract.value.id = '1813752030453710850'
		// 	emits('update:visible', false)
		// 	iframeUrl.value = 'https://smlt.esign.cn/rXv0K2M'
		// 	contractWrite.value = true
		// 	return
		// }

		// 产品维护
		if (step.value === 2) {
			const cycleMap = {}
			newContract.value.list = categoryIdsList.value.reduce((total, item, index) => {
				if (item && item.length) {
					const [classData, typeData, projectData] = categoryIdsMap[`${item[0]}-${item[1]}-${item[2]}`]
					const { projectType, orderAmount, depositAmount, balancePayment, serviceStime, serviceLife, giveMonth } =
						categoryTypeList.value[index]

					let status = false
					if (newContract.value.paymentMethod === 'FULL') {
						// 全款
						if (projectType === 1) {
							// // 代办
							// if (orderAmount) {
							// 	status = true
							// }
							status = true
						} else if (projectType === 2) {
							// 续费
							if (serviceLife && serviceStime) {
								status = true
							}
						}
					} else if (newContract.value.paymentMethod === 'DEPOSIT') {
						// 定金
						if (projectType === 1) {
							// // 代办
							// if (orderAmount) {
							// 	status = true
							// }
							status = true
						} else if (projectType === 2) {
							// 续费
							if (serviceLife && serviceStime) {
								status = true
							}
						}
					}
					if (status) {
						total.push({
							businessType: projectType,
							tenantId: tool.data.get('loginData').tenantId,
							serviceClassId: classData.value,
							serviceTypeId: typeData.value,
							serviceProjectId: projectData.value,
							serviceClassName: classData.label,
							serviceTypeName: typeData.label,
							serviceProjectName: projectData.label,
							orderAmount,
							depositAmount,
							balancePayment,
							serviceStime,
							serviceEtime: serviceEndTime.value(index),
							serviceLife,
							giveMonth
						})
					}

					if (projectType === 2) {
						// 续费
						const classNum = cycleMap[classData.value]
						cycleMap[classData.value] = !classNum ? 1 : classNum + 1
					}
				}
				return total
			}, [])

			if (newContract.value.signMethod === '0') {
				// 电子合同
				if (newContract.value.customerType === 1) {
					// 企业
					if (!newContract.value.id) {
						newContract.value.signType = '1'
					}
				} else if (newContract.value.customerType === 2) {
					// 法人
					newContract.value.signType = ''
				}
			} else if (newContract.value.signMethod === '1') {
				// 纸质合同
				if (!newContract.value.id) {
					newContract.value.contractImg = ''
					newContract.value.voucherImg = ''
				}
				newContract.value.signType = ''
			}

			const classRepeatStatus = Object.values(cycleMap).some((item) => item > 1)
			if (classRepeatStatus) {
				return message.warning('同类型的周期业务只可选择一个！')
			}

			if (!parseFloat(contractAmountSum.value)) {
				return message.warning('合同总金额不能为0')
			}
			if (newContract.value.paymentMethod === 'DEPOSIT' && !parseFloat(depositAmountSum.value)) {
				return message.warning('定金总金额不能为0')
			}
			if (
				newContract.value.contractType === 'TRANS' &&
				newContract.value.paymentMethod === 'DEPOSIT' &&
				parseFloat(depositAmountSum.value) < newContract.value.transDeductionAmount
			) {
				return message.warning('合同定金总金额不能小于历史合同的抵扣金额')
			}
		}

		if (!stepCheck()) {
			message.warning('请完善合同信息')
			return
		}

		// 产品维护或资料上传
		if (
			(step.value === 2 && newContract.value.signMethod === '0') ||
			(step.value === 3 && newContract.value.signMethod === '1')
		) {
			subLoading.value = true
			contractApi
				.addContract(newContract.value)
				.then((res) => {
					newContract.value.id = res.contractId
					emits('update:visible', false)
					if (newContract.value.signMethod === '1') {
						if (isTenantOderControls.value !== null) declarationVisible.value = true
						return emits('finished')
					}
					iframeUrl.value = res.docTemplateFillUrl
					contractWrite.value = true
				})
				.finally(() => {
					subLoading.value = false
				})
		} else {
			step.value++
		}

		// 产品维护
		if (step.value === 2) {
			if (newContract.value.signMethod === '0') {
				await requestTemplateList()
				const templateData = tempTemplateList.value.find((item) => item.templateId === newContract.value.templateId)
				if (templateData) {
					requestServiceProjectListByTemplateId(templateData.id)
				}
			} else if (newContract.value.signMethod === '1') {
				requestServiceProjectList()
			}
		}

		fileCommonFn()
	}
	/**
	 * 下一步之前校验数据是否填写
	 */
	const stepCheck = () => {
		// 产品维护
		if (step.value === 2) {
			if (
				(newContract.value.signMethod === '0' && !newContract.value.templateId) ||
				newContract.value.list.length !== categoryIdsList.value.length ||
				(newContract.value.paymentMethod === 'DEPOSIT' && !newContract.value.balancePaymentTime)
			) {
				return false
			}
		}
		// 资料上传
		if (step.value === 3 && newContract.value.signMethod === '1') {
			if (!newContract.value.contractImg || !newContract.value.voucherImg) {
				return false
			}
		}
		// 签约方维护
		if (step.value === 1) {
			if (
				!newContract.value.firstParty ||
				!newContract.value.firstPartyPerson ||
				!newContract.value.firstPartyMobile ||
				!newContract.value.secondPartyId ||
				!newContract.value.secondPartyPerson ||
				!newContract.value.secondPartyMobile
			) {
				return false
			}
		}
		return true
	}

	const closeContract = () => {
		Modal.confirm({
			title: '提示',
			content: '合同已提交，确认关闭?',
			okText: '确认',
			onOk: () => {
				contractWrite.value = false
				if (isTenantOderControls.value !== null) declarationVisible.value = true
				emits('finished')
			},
			closable: true,
			cancelText: '取消'
		})
	}

	/**
	 * 添加附件信息
	 */
	const declarationVisible = ref(false)
	const activeName = ref('1')
	const isTenantOderControls = ref(null)
</script>
<style lang="less" scoped>
	:deep(.ant-form-item-label > label) {
		white-space: initial;
		height: 36px;
	}
	.serveForm :deep(.ant-form-item) {
		margin-bottom: 12px;
	}
</style>
